package htmlsoup

type SliceSoupNode struct {
	capacity int
	data     []*SoupNode
}

func BuildSliceSoupNode(length, capacity int) SliceSoupNode {
	var v SliceSoupNode
	if capacity < length {
		if length > 0 {
			capacity = length
		} else {
			length = 0
			capacity = 20
		}
	}
	v.capacity = capacity
	v.data = make([]*SoupNode, length, capacity)
	return v
}

func (this *SliceSoupNode) AtIndex(index int) *SoupNode {
	length := len(this.data)
	if index < 0 {
		index = length - index
	}
	if index >= 0 && index < len(this.data) {
		return this.data[index]
	} else {
		return nil
	}
}

func (this *SliceSoupNode) Index(src *SoupNode) int {
	for i, s := range this.data {
		if src.id == s.id {
			return i
		}
	}
	return -1
}

func (this *SliceSoupNode) Len() int {
	return len(this.data)
}

func (this *SliceSoupNode) Contains(src *SoupNode) bool {
	return this.Index(src) >= 0
}

func (this *SliceSoupNode) AppendSlice(src []*SoupNode) {
	destLength := len(this.data)
	srcLength := len(src)
	combinedLength := destLength + srcLength
	if combinedLength >= cap(this.data) {
		temp := make([]*SoupNode, combinedLength, combinedLength+this.capacity)
		copy(temp, this.data)
		this.data = temp
	} else {
		this.data = this.data[:combinedLength]
	}
	di := destLength
	for _, n := range src {
		this.data[di] = n
		di++
	}
}

func (this *SliceSoupNode) Append(src *SoupNode) {
	length := len(this.data)
	if length == cap(this.data) {
		temp := make([]*SoupNode, length+1, length+this.capacity)
		copy(temp, this.data)
		this.data = temp
	} else {
		this.data = this.data[:length+1]
	}
	this.data[length] = src
}

func (this *SliceSoupNode) Sort() {
	var temp *SoupNode
	var i, j, last int
	last = len(this.data) - 1
	for i = 0; i < last; i++ {
		for j = i + 1; j <= last; j++ {
			if this.data[i].ID() > this.data[j].ID() {
				// swap
				temp = this.data[i]
				this.data[i] = this.data[j]
				this.data[j] = temp
			}
		}
	}
}

func (this *SliceSoupNode) Delete(index int) {
	length := len(this.data)
	if index < 0 {
		index = length - index
	}
	if index >= 0 {
		if index < length-1 {
			for si := index + 1; si < length; {
				this.data[index] = this.data[si]
				index++
				si++
			}
			this.data = this.data[:length-1]
		}
	}
}
